package t2.server;

import java.util.concurrent.Callable;

import t2.server.xbee.XBeePort;

import com.rapplogic.xbee.api.AtCommand;
import com.rapplogic.xbee.api.AtCommandResponse;
import com.rapplogic.xbee.api.PacketListener;
import com.rapplogic.xbee.api.XBee;
import com.rapplogic.xbee.api.XBeeAddress64;
import com.rapplogic.xbee.api.XBeeResponse;

public class DoGet64 implements Callable<XBeeAddress64> {
    /* This number will never change.  Keeping this variable static
     * will cause this function to just return. */
    static boolean responseReceived;
    private XBeeAddress64 addr64;
    private int[] sh, sl;
    int nop = 0;

    PacketListener SH = new PacketListener() {
        @Override
        public void processResponse(XBeeResponse response) {
            AtCommandResponse atResp = (AtCommandResponse) response;
            if (atResp.getCommand().equals("SH")) {
                setSh(atResp.getValue());
                responseReceived = true;
            }
        }
    };

    PacketListener SL = new PacketListener() {
        @Override
        public void processResponse(XBeeResponse response) {
            AtCommandResponse atResp = (AtCommandResponse) response;
            if (atResp.getCommand().equals("SL")) {
                setSl(atResp.getValue());
                responseReceived = true;
            }
        }
    };

    @Override
    public XBeeAddress64 call() throws Exception {
        XBee xbee = XBeePort.getXBeePort().getXbee();
        xbee.addPacketListener(SH);
        xbee.sendAsynchronous(new AtCommand("SH"));
        do {
            Thread.sleep(1);
            nop++;
        }
        while (!responseReceived && nop < 6000);
        responseReceived = false;
        xbee.removePacketListener(SH);
        xbee.clearResponseQueue();

        xbee.addPacketListener(SL);
        xbee.sendAsynchronous(new AtCommand("SL"));
        do {
            Thread.sleep(1);
            nop++;
        }
        while (!responseReceived && nop < 6000);
        responseReceived = false;
        xbee.removePacketListener(SL);
        xbee.clearResponseQueue();


        int[] serial = new int[getSh().length + getSl().length];
        System.arraycopy(getSh(), 0, serial, 0, getSh().length);
        System.arraycopy(getSl(), 0, serial, getSh().length, getSl().length);

        return (new XBeeAddress64(serial));
    }

    public int[] getSh() {
        return sh;
    }

    public void setSh(int[] sh) {
        this.sh = sh;
    }

    public XBeeAddress64 getAddr64() {
        return addr64;
    }

    public void setAddr64(XBeeAddress64 addr64) {
        this.addr64 = addr64;
    }

    public int[] getSl() {
        return sl;
    }

    public void setSl(int[] sl) {
        this.sl = sl;
    }

}
